package com.lmc.recreation;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.lmc.R;
import com.lmc.adapter.RecreationListAdapter;
import com.lmc.entity.RecreationDetails;
import com.lmc.util.GlideUtil;
import com.lmc.util.JsonManager;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.page.view.ProgressDialog;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.ActivityStack;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.app.util.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 娱乐的详情页面
 */
public class RecreationActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private ImageView back;
    private TextView name;
    private ImageView icon;
    private ListView listView;
    private RecreationListAdapter adapter;
    private List<RecreationDetails.DataBean.ItemsBean> list = new ArrayList<>();
    private String id;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recreation);
        initView();
        id = getIntent().getStringExtra("id");
        setStatusBar();
        adapter = new RecreationListAdapter(this, list);
        listView.setAdapter(adapter);
        back.setOnClickListener(this);
        ActivityStack.addActivity(this);
        listView.setOnItemClickListener(this);
        Get();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStack.removeActivity(this);
    }

    private void Get() {
        JSONObject params = new JSONObject();
        params.put("skill_id", id);

        HttpRequest.getService().getMediaDetails(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.e("-----------", "获取娱乐模块列表：" + string);
                    RecreationDetails details = JsonManager.parseJson(string, RecreationDetails.class);
                    list.clear();
                    list.addAll(details.getData().getItems());
                    adapter.notifyDataSetChanged();

                    name.setText(details.getData().getName());
                    GlideUtil.setImg(RecreationActivity.this, icon, details.getData().getImage());
                } catch (Exception e) {
                    Log.e("-----", e.toString());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });

    }


    /**
     * 设置导航栏：沉浸式
     */
    @TargetApi(21)
    public void setStatusBar() {
        //5.0及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(0);
            //4.4到5.0
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
    }

    protected ProgressDialog showProgress(boolean cancelable) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this, cancelable, false);
        }
        if (!progressDialog.isShowing()) {
            if (!this.isFinishing()) {//如果页面没有被关闭则往下执行
                progressDialog.show();
            }
        }
        return progressDialog;
    }

    public void hideProgress() {
        if (progressDialog != null && progressDialog.isShowing()) {
            if (!this.isFinishing()) {
                progressDialog.dismiss();
            }
        }
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.back);
        name = (TextView) findViewById(R.id.name);
        icon = (ImageView) findViewById(R.id.icon);
        listView = (ListView) findViewById(R.id.listView);
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) back.getLayoutParams();
        layoutParams.topMargin = StatusBarUtil.getStatusBarHeight(this);
        back.setLayoutParams(layoutParams);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back) {
            finish();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        showProgress(true);
        //提交播放
        JSONObject params = new JSONObject();
        RecreationDetails.DataBean.ItemsBean bean = list.get(position);
        params.put("robot_id", SharePreferenceUtil.getDeviceId(this));

        params.put("media_id", RecreationActivity.this.id);
        params.put("audio_id", bean.getId());

        HttpRequest.getService().mediaSkillPlay(HttpRequest.getDefaultBody(params)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                hideProgress();
                try {
                    String string = response.body().string();
//                    Log.e("-----------", "播放返回：" + string);
                    BaseBean baseBean = JsonManager.parseJson(string, BaseBean.class);
                    if (baseBean.getCode() != 200) {
                        ToastUtil.showTextToast(RecreationActivity.this, baseBean.getMsg());
                    } else {
                        update(position);
                    }
                } catch (Exception e) {
                    Log.e("-----", e.toString());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                hideProgress();
                ToastUtil.showTextToast(RecreationActivity.this, getString(R.string.network_error));
            }
        });
    }

    private void update(int position) {
        if (list.size() <= position) return;
        for (RecreationDetails.DataBean.ItemsBean recreation : list) {
            recreation.setTag(0);
        }
        list.get(position).setTag(1);
        adapter.notifyDataSetChanged();
    }
}
